﻿// Copyright © Microsoft Corporation.  All Rights Reserved.
// This code released under the terms of the 
// Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)

using System.Windows;
using System.Windows.Input;
using System.Windows.Interactivity;
using System.Windows.Media.Effects;

namespace TheOliver.Controls
{
    public class BlurHoverBehavior : Behavior<UIElement>
    {
        BlurEffect effect = null;

        public BlurHoverBehavior()
            : base()
        {
            effect = new BlurEffect() { Radius = BlurRadius };
        }

        #region BlurRadius (DependencyProperty)

        /// <summary>
        /// RadThe Blur Radius to use for the Blur Effect
        /// </summary>
        public double BlurRadius
        {
            get { return (double)GetValue(BlurRadiusProperty); }
            set { SetValue(BlurRadiusProperty, value); }
        }
        public static readonly DependencyProperty BlurRadiusProperty =
            DependencyProperty.Register("BlurRadius", typeof(double), typeof(BlurHoverBehavior),
            new PropertyMetadata((double)2, new PropertyChangedCallback(OnBlurRadiusChanged)));

        private static void OnBlurRadiusChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((BlurHoverBehavior)d).OnBlurRadiusChanged(e);
        }

        protected virtual void OnBlurRadiusChanged(DependencyPropertyChangedEventArgs e)
        {
            effect.Radius = BlurRadius;
        }

        #endregion

        protected override void OnAttached()
        {
            base.OnAttached();

            this.AssociatedObject.MouseEnter += new MouseEventHandler(AssociatedObject_MouseEnter);
            this.AssociatedObject.MouseLeave += new MouseEventHandler(AssociatedObject_MouseLeave);
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();

            this.AssociatedObject.MouseEnter -= new MouseEventHandler(AssociatedObject_MouseEnter);
            this.AssociatedObject.MouseLeave -= new MouseEventHandler(AssociatedObject_MouseLeave);
        }

        #region Events
        void AssociatedObject_MouseLeave(object sender, MouseEventArgs e)
        {
            this.AssociatedObject.Effect = null;
        }

        void AssociatedObject_MouseEnter(object sender, MouseEventArgs e)
        {
            this.AssociatedObject.Effect = effect;
        }
        #endregion
    }
}
